package com.lsa.letcode.the23.mergeKsortedLists;

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

import com.lsa.letcode.common.ListNode;


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
    	if (lists == null || lists.length < 1){
    		return null;
    	}
    	ListNode result = new ListNode(Integer.MIN_VALUE); // dummy
    	ListNode current = result;
    	
    	Queue<ListNode> q = new PriorityQueue<>(lists.length, new Comparator<ListNode>() {
			@Override
			public int compare(ListNode o1, ListNode o2) {
				return o1.val - o2.val;
			}
		});
    	for (int i = 0; i < lists.length; i++) {
    		ListNode n = lists[i];
			if (n != null) {
    			q.add(n);
    		}
		}
    	
    	while(!q.isEmpty()){
    		ListNode n = q.poll();
    		current.next = n;
    		current = current.next;
    		
    		if (n.next != null){
    			q.add(n.next);
    		}
    	}
        return result.next;
    }
}